/**
 *====================================================
 * 文件名称: FinanceAppActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月26日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.timevale.esign.sdk.tech.bean.OrganizeBean;
import com.timevale.esign.sdk.tech.bean.PersonBean;
import com.timevale.esign.sdk.tech.bean.PosBean;
import com.timevale.esign.sdk.tech.bean.SignPDFFileBean;
import com.timevale.esign.sdk.tech.bean.result.AddAccountResult;
import com.timevale.esign.sdk.tech.bean.result.AddSealResult;
import com.timevale.esign.sdk.tech.bean.result.FileDigestSignResult;
import com.timevale.esign.sdk.tech.bean.result.Result;
import com.timevale.esign.sdk.tech.bean.seal.OrganizeTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.PersonTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.SealColor;
import com.timevale.esign.sdk.tech.impl.constants.OrganRegType;
import com.timevale.esign.sdk.tech.impl.constants.SignType;
import com.timevale.esign.sdk.tech.service.AccountService;
import com.timevale.esign.sdk.tech.service.MobileService;
import com.timevale.esign.sdk.tech.service.SealService;
import com.timevale.esign.sdk.tech.service.SelfSignService;
import com.timevale.esign.sdk.tech.service.UserSignService;
import com.timevale.esign.sdk.tech.service.factory.AccountServiceFactory;
import com.timevale.esign.sdk.tech.service.factory.MobileServiceFactory;
import com.timevale.esign.sdk.tech.service.factory.SealServiceFactory;
import com.timevale.esign.sdk.tech.service.factory.SelfSignServiceFactory;
import com.timevale.esign.sdk.tech.service.factory.UserSignServiceFactory;
import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.context.FinanceBaseAction;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.SignatureInfoEntity;
import com.yuexunit.finance.member.entity.lexicon.AuditStateEnum;
import com.yuexunit.finance.member.entity.lexicon.AuthenticationEnum;
import com.yuexunit.finance.project.action.v1.model.output.SealsDetail;
import com.yuexunit.finance.project.action.v1.model.output.SignFileSealInfoDetail;
import com.yuexunit.finance.project.action.v1.model.output.SignFileSeals;
import com.yuexunit.finance.project.action.v1.model.output.SignPdfPagePicDetail;
import com.yuexunit.finance.project.action.v1.model.output.SignPdfPicDetail;
import com.yuexunit.finance.project.action.v1.model.output.SignatureAuditRecordDetail;
import com.yuexunit.finance.project.action.v1.model.output.SignatureDetail;
import com.yuexunit.finance.project.action.v1.model.output.SignatureInfo;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.PickupApplicationWarehouseEntity;
import com.yuexunit.finance.project.entity.SignatureCallbackRecordEntity;
import com.yuexunit.finance.project.entity.SignatureEntity;
import com.yuexunit.finance.project.entity.lexicon.FileSignStateEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceConstractStateEnum;
import com.yuexunit.finance.project.entity.lexicon.WarePickupStateEnum;
import com.yuexunit.finance.project.service.FinanceSignatureInfoService;
import com.yuexunit.finance.project.service.FinanceSignatureService;
import com.yuexunit.finance.project.service.PickupApplicationWarehouseService;
import com.yuexunit.finance.project.service.SignatureCallbackRecordService;
import com.yuexunit.finance.seal.entity.lexion.SealTypeEnum;
import com.yuexunit.finance.seal.entity.lexion.SignStateEnum;
import com.yuexunit.finance.system.entity.SignFileInfoEntity;
import com.yuexunit.finance.system.entity.SignFileSealInfoEntity;
import com.yuexunit.finance.system.service.SignFileInfoService;
import com.yuexunit.finance.system.service.SignFileSealInfoService;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.fs.service.TransferService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;


/** 
 * @ClassName: FinanceSignatureActionApi 
 * @Description:   指尖金融电子签章管理
 * @author: NTBK-021-1010
 * @date: 2016年10月31日 下午3:39:49  
 */
@SuppressWarnings("restriction")
@Implements(FinanceSignatureActionApi.class)
public class FinanceSignatureActionApiImpl  extends FinanceBaseAction implements FinanceSignatureActionApi{

	private Logger LOG = LoggerFactory.getLogger(FinanceSignatureActionApiImpl.class);

	private FinanceSignatureService signatureService= ComponentFactory.loadClass(FinanceSignatureService.class);

//	private EsignsdkService esignsdkService = EsignsdkServiceFactory.instance();

	private AccountService accountService = AccountServiceFactory.instance();

	private SealService sealService = SealServiceFactory.instance();

//	private static SignService signService = SignServiceFactory.instance();
	
	private UserSignService userSignService = UserSignServiceFactory.instance();
	
	private SelfSignService selfSignService = SelfSignServiceFactory.instance();
	
//	private SealInfoService sealInfoService = ComponentFactory.loadClass(SealInfoService.class);
	
	private TransferService fileService = ComponentFactory.loadClass(TransferService.class);
	
//	private FinanceFilesInfoService financeFilesInfoService = ComponentFactory.loadClass(FinanceFilesInfoService.class);
	
	private SignFileInfoService signFileInfoService = ComponentFactory.loadClass(SignFileInfoService.class);
	
	private MobileService mobileService = MobileServiceFactory.instance();
	
	private SignFileSealInfoService signFileSealInfoService = ComponentFactory.loadClass(SignFileSealInfoService.class);

//	    private SignFileStreamResult signFileStreamResult=ComponentFactory.loadClass(SignFileStreamResult .class);

	private TransferService transferService = ComponentFactory.loadClass(TransferService.class);
	
	private SignatureCallbackRecordService signatureCallbackRecordService = ComponentFactory.loadClass(SignatureCallbackRecordService.class);
	
	private PickupApplicationWarehouseService pickupApplicationWarehouseService = ComponentFactory.loadClass(PickupApplicationWarehouseService.class);

	@Override
	public void deleteAccount(String accountId) {
		Result r = accountService.deleteAccount(accountId);
		LOG.error("注销账户:" + r.getErrCode() + "" + r.getMsg());
	}
	
	@Override
	public SignatureDetail inquireSealDetail(Long enterpriseId, Integer modelType, Integer sealType) throws Exception {
		if (null == enterpriseId) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		
		SignatureEntity se = signatureService.inquireFinanceSignatureEntity(enterpriseId, modelType, SealTypeEnum.valueOf(sealType));
		if(se == null) {
			return null;
		}
		SignatureDetail sd = new SignatureDetail();
		BeanUtils.copyProperties(se, sd);
		sd.setAuditState(se.getAuditState().ordinal());
		sd.setSealType(se.getSealType().ordinal());
		
		//获取签章地址
//		JSONObject jsonObject =  JSONObject.fromObject(se.getSealData()); 
//		String data = jsonObject.getString("data");
//		byte[] asBytes = Base64.getDecoder().decode(se.getSealData());
//		System.out.println(asBytes);
//		String str = new String(asBytes, "utf-8");
//		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
//		Matcher m = p.matcher(str);
//		String decodeData = m.replaceAll("");
//		System.out.println(decodeData);
//		p = Pattern.compile("<data>(.*)</data>");  
//		m = p.matcher(decodeData); 
//		System.out.println(m);
//		while(m.find()){  
			sd.setSealSrc("data:image/png;base64," + se.getSealData());
			sd.setData(se.getSealData());
//			sd.setData(m.group(1));
//		}
		
		return sd;
	}
	
	@Override
	public SealsDetail sealGetSeals(Long enterpriseId) {
		if (null == enterpriseId) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		List<SignatureEntity> signatureList = signatureService.inquireFinanceSignatureEntityList(enterpriseId);
		SealsDetail s = new SealsDetail();
		for (SignatureEntity se : signatureList) {
			SignatureDetail sd = new SignatureDetail();
			BeanUtils.copyProperties(se, sd);
			sd.setSealType(se.getSealType().ordinal());
			sd.setSealSrc("data:image/png;base64," + se.getSealData());
			sd.setData(se.getSealData());
			sd.setImgUrl("data:image/png;base64," + se.getSealData());
			sd.setId1(sd.getId().intValue());
			sd.setSealName(se.getSealType().getValue());
			sd.setTemplateName(se.getSealType().getValue());
			sd.setModifyDate(DateUtil.nowDate());
			sd.setCreateDate(DateUtil.nowDate());
			if (se.getSealType() == SealTypeEnum.ENTERPRISE) {
				sd.setType(1);
				sd.setIsDefault(1);
			}
			
			if (se.getSealType() == SealTypeEnum.PERSONAL) {
				sd.setHeight(95);
				sd.setWidth(95);
			} else {
				sd.setHeight(159);
				sd.setWidth(159);
			}
			s.getMsg().add(sd);
		}
		return s;
	}
	
	@Override
	@Transactional
	public void auditSeal(Long id, Boolean auditState, String remark) {
		SignatureEntity se = signatureService.inquireFinanceSignatureEntity(id);
		if (AuditStateEnum.UNAUDIT != se.getAuditState()) {
			throw new BusinessException("只有未审批的印章才能进行审批！");
		}
		//审批记录
		SignatureCallbackRecordEntity scre = new SignatureCallbackRecordEntity();
		scre.setEnterpriseId(se.getEnterpriseId());
		scre.setSealType(se.getSealType());
		scre.setOperatDateTime(DateUtil.now());
		scre.setOperator(FinanceSessionContext.getAccountFullName());
		scre.setRemark(remark);
		if (Boolean.FALSE == auditState) {
			se.setAuditState(AuditStateEnum.REFUSE);
			se.setEnabled(Boolean.FALSE);
			se.setAuditDateTime(DateUtil.now());
			signatureService.updateSignatureEntity(se);
			
			scre.setRecordType(2); //拒绝
		} else if (Boolean.TRUE == auditState) {
			se.setAuditState(AuditStateEnum.PASS);
			se.setEnabled(Boolean.TRUE);
			se.setAuditDateTime(DateUtil.now());
			signatureService.updateSignatureEntity(se);
			
			scre.setRecordType(3); //同意
		}
		
		signatureCallbackRecordService.createSignatureCallbackRecord(scre);
	}
	
	@Override
	public void testSign() throws Exception {
		SignatureEntity se = signatureService.inquireFinanceSignatureEntity(15L, null, SealTypeEnum.PERSONAL);
		JSONObject jsonObject =  JSONObject.fromObject(se.getSealData()); 
		String data = jsonObject.getString("data");
		byte[] asBytes = Base64.getDecoder().decode(data);
		System.out.println(asBytes);
		String str = new String(asBytes, "utf-8");
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(str);
		String decodeData = m.replaceAll("");
		System.out.println(decodeData);
		p = Pattern.compile("<data>(.*)</data>");  
		m = p.matcher(decodeData); 
		System.out.println(m);
		while(m.find()){  
			System.out.println(m.group(1));  
		}
	}

	@Override
	@Transactional
	public void addOrganize() throws Exception{
		// 使用初始化设置的项目编号和项目验证码做项目账户登录
//		LoginResult loginResult = esignsdkService.login();
		//创建企业账户   连接e签宝生成证书,返回账户唯一标识       
		List<EnterpriseEntity> list = enterpriseService.inquireAuditedEnterpriseList();
		//查询平台是否生成电子印章数据
		List<SignatureEntity> signatureList = signatureService.inquireFinanceSignatureEntityList(null);
		Map<Long,SignatureEntity> signatureMap = new HashMap<Long,SignatureEntity>();
		if(signatureList != null && signatureList.size() > 0){
			for(SignatureEntity dto:signatureList){
				if(!signatureMap.containsKey(dto.getEnterpriseId()))
					signatureMap.put(dto.getEnterpriseId(), dto);
			}
		}

		//企业注册E签宝  && 创建电子印章
		for(EnterpriseEntity dto: list){
			if (AuthenticationEnum.ACSUCCESS != dto.getAuthentication()) {
				continue;
			}
			if(!signatureMap.containsKey(dto.getEnterpriseId())){
				addOrganize(dto);
				addAccount(dto);
				createEnterpriseTemplateSeal(dto.getEnterpriseId(), null, null, 1, null, 1);
				createEnterpriseTemplateSeal(dto.getEnterpriseId(), null, null, 2, null, 1);
				createEnterpriseTemplateSeal(dto.getEnterpriseId(), null, null, 3, null, 1);
				createEnterpriseTemplateSeal(dto.getEnterpriseId(), null, null, 4, null, 1);
				SignatureEntity signatureEntity1 = signatureService.inquireFinanceSignatureEntity(dto.getEnterpriseId(), null, SealTypeEnum.valueOf(1));
				SignatureEntity signatureEntity2 = signatureService.inquireFinanceSignatureEntity(dto.getEnterpriseId(), null, SealTypeEnum.valueOf(2));
				SignatureEntity signatureEntity3 = signatureService.inquireFinanceSignatureEntity(dto.getEnterpriseId(), null, SealTypeEnum.valueOf(3));
				SignatureEntity signatureEntity4 = signatureService.inquireFinanceSignatureEntity(dto.getEnterpriseId(), null, SealTypeEnum.valueOf(4));
				if (signatureEntity1 != null) {
					signatureEntity1.setAuditState(AuditStateEnum.UNKNOWN);
					signatureEntity1.setModelType(1);
					signatureService.updateSignatureEntity(signatureEntity1);
				}
				if (signatureEntity2 != null) {
					signatureEntity2.setAuditState(AuditStateEnum.UNKNOWN);
					signatureEntity2.setModelType(1);
					signatureService.updateSignatureEntity(signatureEntity2);
				}
				if (signatureEntity3 != null) {
					signatureEntity3.setAuditState(AuditStateEnum.UNKNOWN);
					signatureEntity3.setModelType(1);
					signatureService.updateSignatureEntity(signatureEntity3);
				}
				if (signatureEntity4 != null) {
					signatureEntity4.setAuditState(AuditStateEnum.UNKNOWN);
					signatureEntity4.setModelType(1);
					signatureService.updateSignatureEntity(signatureEntity4);
				}
			}
		}
	}

//	@Override
//	@Transactional
//	public void updateOrganize() throws Exception {
//
//	}

	/** 
	 * @Title: addOrganize   创建e签宝企业账户
	 * @param devId   开发者id
	 * @param enterprise  企业对象
	 * @return: void
	 */
	private void addOrganize(EnterpriseEntity enterprise) {
//		if(!StringUtils.isEmpty(enterprise.getBusinessLicence())){   //营业执照不能为空

			OrganizeBean org = new OrganizeBean();
//			org.setMobile(enterprise.getMobile()).setName(enterprise.getEnterpriseName()).setRegType(OrganRegType.REGCODE)
//			.setOrganCode(enterprise.getBusinessLicence()).setLegalName(enterprise.getLegalPerson())
//			.setLegalIdNo(enterprise.getLegalIdcard()).setUserType(2); //enterprise.getCertificate()
			org.setName(enterprise.getEnterpriseName()).setMobile(enterprise.getMobile()).
			setOrganCode(enterprise.getCodeUSC()).setRegType(OrganRegType.MERGE).setLegalName(enterprise.getLegalPerson())
			.setLegalIdNo(enterprise.getLegalIdcard()).setUserType(2);

			LOG.info("name:" + org.getName());
			LOG.info("mobile:" + org.getMobile());
			LOG.info("organCode:" + org.getOrganCode());
			LOG.info("regType:" + org.getRegType());
			LOG.info("legalName:" + org.getLegalName());
			LOG.info("legalIdNo:" + org.getLegalIdNo());
			LOG.info("userType:" + org.getUserType());

			AddAccountResult r = accountService.addAccount(org);
			LOG.info("======================="+enterprise.getEnterpriseName() + enterprise.getEnterpriseId() + r.getErrCode() + r.getMsg());
			if(r.getErrCode() == 0){  //创建成功
				createSignature(r.getAccountId(), enterprise);
			} else {
				LOG.info(enterprise.getEnterpriseName() + r.getErrCode() + r.getMsg());
				org.setRegType(OrganRegType.REGCODE).setOrganCode(enterprise.getBusinessLicence());
				LOG.info("name:" + org.getName());
				LOG.info("mobile:" + org.getMobile());
				LOG.info("organCode:" + org.getOrganCode());
				LOG.info("regType:" + org.getRegType());
				LOG.info("legalName:" + org.getLegalName());
				LOG.info("legalIdNo:" + org.getLegalIdNo());
				LOG.info("userType:" + org.getUserType());
				r = accountService.addAccount(org);
				if(r.getErrCode() == 0){  //创建成功
					createSignature(r.getAccountId(), enterprise);
				} else {
					LOG.info(enterprise.getEnterpriseName() + r.getErrCode() + r.getMsg());
				}
			}
//		}
	}
	
	private void createSignature(String accountId, EnterpriseEntity enterprise){
		//企业印章
		SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterprise.getEnterpriseId(), null, SealTypeEnum.valueOf(2));
		if (null == signatureEntity) {
			signatureEntity = new SignatureEntity();
		}
		signatureEntity.setEaccount(accountId);
		signatureEntity.setEnterpriseId(enterprise.getEnterpriseId());
		signatureEntity.setEnterpriseName(enterprise.getEnterpriseName());  //取企业简称 getEnterpriseShortName
		signatureEntity.setCreateDateTime(new Date());
		signatureEntity.setLegalPerson(enterprise.getLegalPerson());
		signatureEntity.setSealType(SealTypeEnum.ENTERPRISE);
		signatureService.createFinanceGroupEntity(signatureEntity);
		
		//财务印章
		SignatureEntity signatureEntity1 = signatureService.inquireFinanceSignatureEntity(enterprise.getEnterpriseId(), null, SealTypeEnum.valueOf(3));
		if (null == signatureEntity1) {
			signatureEntity1 = new SignatureEntity();
		}
		signatureEntity1.setEaccount(accountId);
		signatureEntity1.setEnterpriseId(enterprise.getEnterpriseId());
		signatureEntity1.setEnterpriseName(enterprise.getEnterpriseName());  //取企业简称 getEnterpriseShortName
		signatureEntity1.setCreateDateTime(new Date());
		signatureEntity1.setLegalPerson(enterprise.getLegalPerson());
		signatureEntity1.setSealType(SealTypeEnum.FINANCE);
		signatureService.createFinanceGroupEntity(signatureEntity1);
		
		//其他印章
		SignatureEntity signatureEntity2 = signatureService.inquireFinanceSignatureEntity(enterprise.getEnterpriseId(), null, SealTypeEnum.valueOf(4));
		if (null == signatureEntity2) {
			signatureEntity2 = new SignatureEntity();
		}
		signatureEntity2.setEaccount(accountId);
		signatureEntity2.setEnterpriseId(enterprise.getEnterpriseId());
		signatureEntity2.setEnterpriseName(enterprise.getEnterpriseName());  //取企业简称 getEnterpriseShortName
		signatureEntity2.setCreateDateTime(new Date());
		signatureEntity2.setLegalPerson(enterprise.getLegalPerson());
		signatureEntity2.setSealType(SealTypeEnum.OTHERS);
		signatureService.createFinanceGroupEntity(signatureEntity2);
	}
	
	/** 
	 * @Title: addOrganize   创建e签宝个人账户
	 * @param devId   开发者id
	 * @param enterprise  企业对象
	 * @return: void
	 */
	private void addAccount(EnterpriseEntity enterprise) {
		PersonBean pb = new PersonBean();
		pb.setMobile(enterprise.getMobile())
		.setName(enterprise.getLegalPerson())
		.setIdNo(enterprise.getLegalIdcard())
		.setOrgan(enterprise.getEnterpriseName());
		
		AddAccountResult r = accountService.addAccount(pb);
		if(r.getErrCode() == 0){  //创建成功
			SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterprise.getEnterpriseId(), null, SealTypeEnum.valueOf(1));
			if (null == signatureEntity) {
				signatureEntity = new SignatureEntity();
			}
			signatureEntity.setEaccount(r.getAccountId());
			signatureEntity.setEnterpriseId(enterprise.getEnterpriseId());
			signatureEntity.setEnterpriseName(enterprise.getEnterpriseName());  //取企业简称 getEnterpriseShortName
			signatureEntity.setCreateDateTime(new Date());
			signatureEntity.setSealType(SealTypeEnum.PERSONAL);
			signatureEntity.setLegalPerson(enterprise.getLegalPerson());
			signatureService.createFinanceGroupEntity(signatureEntity);
		} else {
			LOG.error("企业ID"+enterprise.getEnterpriseName()+":"+r.getErrCode()+""+r.getMsg());
		}
	}

	@Override
	@Transactional
	public void createTemplateSeal(Long enterpriseId) throws Exception {
		// 使用初始化设置的项目编号和项目验证码做项目账户登录
		SignatureEntity signatureEntity=signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.ENTERPRISE);
		if(signatureEntity!=null){
			AddSealResult addSealResult= sealService.addTemplateSeal(signatureEntity.getEaccount(), OrganizeTemplateType.STAR, SealColor.RED,signatureEntity.getLegalPerson(),new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
			if(addSealResult.getErrCode()==0){
				signatureEntity.setSealData(addSealResult.getSealData());
				signatureService.updateSignatureEntity(signatureEntity);
			}else{
				LOG.error("企业ID"+enterpriseId+""+addSealResult.getMsg());
			}
		}
	}
	
	@Override
	@Transactional
	public void createTemplateSealPersonal(Long enterpriseId) throws Exception {
		// 使用初始化设置的项目编号和项目验证码做项目账户登录
		SignatureEntity signatureEntity=signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.PERSONAL);
		if(signatureEntity!=null){
			AddSealResult addSealResult= sealService.addTemplateSeal(signatureEntity.getEaccount(), PersonTemplateType.SQUARE, SealColor.RED);
			if(addSealResult.getErrCode()==0){
				signatureEntity.setSealData(addSealResult.getSealData());
				signatureService.updateSignatureEntity(signatureEntity);
			}else{
				LOG.error("企业ID"+enterpriseId+""+addSealResult.getMsg());
			}
		}
	}

	@Override
	@Transactional
	public void createEnterpriseTemplateSeal(Long enterpriseId, String hText, String qText, Integer sealType, String remark, Integer modelType)
			throws Exception {
		if (enterpriseId == null) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		if (1 == sealType) {
			createLegalPersonTemplateSeal(enterpriseId, remark);
		} else {
			EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
			if (AuthenticationEnum.ACSUCCESS != enterprise.getAuthentication()) {
				throw new BusinessException("未实名认证不可制章！");
			}
			
			// 使用初始化设置的项目编号和项目验证码做项目账户登录
			SignatureEntity signatureEntity=signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.valueOf(sealType));
			
			if(signatureEntity != null){
				if (AuditStateEnum.UNKNOWN != signatureEntity.getAuditState() && AuditStateEnum.REFUSE != signatureEntity.getAuditState() && AuditStateEnum.CALLBACK != signatureEntity.getAuditState()) {
					throw new BusinessException("已提交的签章不允许继续修改！");
				}
				AddSealResult addSealResult= sealService.addTemplateSeal(signatureEntity.getEaccount(), OrganizeTemplateType.STAR, SealColor.RED, hText, qText);
				
				if(addSealResult.getErrCode()==0){
					signatureEntity.setSealData(addSealResult.getSealData());
					signatureEntity.setEnabled(Boolean.TRUE);
					signatureEntity.sethText(hText);
					signatureEntity.setqText(qText);
					signatureEntity.setAuditState(AuditStateEnum.UNAUDIT);
					signatureEntity.setSubmitDateTime(DateUtil.now());
					signatureEntity.setModelType(modelType);
					signatureService.updateSignatureEntity(signatureEntity);
				}else{
					LOG.error("企业ID" + enterpriseId  + ":" + addSealResult.getMsg());
					throw new BusinessException(addSealResult.getMsg());
				}
			} else {
				
			}
		}
	}
	
	@Override
	public String previewEnterpriseTemplateSeal(String hText, String qText, Long enterpriseId, Integer sealType, String remark)
			throws Exception {
		if(enterpriseId == null) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		SignatureEntity signatureEntity=signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.valueOf(sealType));
		if (1 == sealType) {
			AddSealResult addSealResult = sealService.addTemplateSeal(signatureEntity.getEaccount(), PersonTemplateType.SQUARE, SealColor.RED);
			return "data:image/png;base64," + addSealResult.getSealData();
		} else {
			AddSealResult addSealResult= sealService.addTemplateSeal(signatureEntity.getEaccount(), OrganizeTemplateType.STAR, SealColor.RED, hText, qText);
			return "data:image/png;base64," + addSealResult.getSealData();
		}
	}
	
	@Override
	@Transactional
	public void callBackSignature(Long enterpriseId, Integer sealType, String remark) {
		SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.valueOf(sealType));
		if (null != signatureEntity) {
			signatureEntity.setAuditState(AuditStateEnum.CALLBACK);
			signatureEntity.setAuditDateTime(DateUtil.now());
			signatureService.updateSignatureEntity(signatureEntity);
			
			//打回记录
			SignatureCallbackRecordEntity scre = new SignatureCallbackRecordEntity();
			scre.setEnterpriseId(enterpriseId);
			scre.setSealType(SealTypeEnum.valueOf(sealType));
			scre.setOperatDateTime(DateUtil.now());
			scre.setOperator(FinanceSessionContext.getAccountFullName());
			scre.setRemark(remark);
			scre.setRecordType(1);
			
			signatureCallbackRecordService.createSignatureCallbackRecord(scre);
		}
	}

	@Transactional
	@Override
	public void createLegalPersonTemplateSeal(Long enterpriseId, String remark) throws Exception {
		if (enterpriseId == null) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		// 使用初始化设置的项目编号和项目验证码做项目账户登录
		SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.PERSONAL);
		if(signatureEntity!=null){
//			AddSealResult addSealResult = sealService.addTemplateSeal(loginResult.getAccountId(), signatureEntity.getEaccount(), PersonTemplateType.SQUARE, SealColor.RED);
			AddSealResult addSealResult = sealService.addTemplateSeal(signatureEntity.getEaccount(), PersonTemplateType.SQUARE, SealColor.RED);
			if(addSealResult.getErrCode()==0){
				signatureEntity.setSealData(addSealResult.getSealData());
				signatureEntity.setEnabled(Boolean.TRUE);
				signatureEntity.setAuditState(AuditStateEnum.UNAUDIT);
				signatureEntity.setSubmitDateTime(DateUtil.now());
				signatureService.updateSignatureEntity(signatureEntity);
//				SealInfoEntity sie = new SealInfoEntity();
//				sie.setEnterpriseId(signatureEntity.getEnterpriseId());
//				sie.setSealType(SealTypeEnum.PERSONAL);
//				sie.setRemark(remark);
//				sie.setSealDate(addSealResult.getSealData());
//				sie.setSignId(signatureEntity.getId());
//				sealInfoService.createSealInfo(sie);
			}else{
				LOG.error("企业ID"+enterpriseId+""+addSealResult.getMsg());
			}
		}
	}

	/** 
	 * @Title: createSealOrganize   创建企业印章
	 * @param devId     开发者账号
	 * @param accountId 企业账号
	 * @param templateType 印章类型
	 * @param color 印章颜色
	 * @param hText 横向文字
	 * @param qText 下弦文
	 * @return
	 * @return: AddSealResult
	 */
//	private AddSealResult createSealOrganize(String accountId,
//			String templateType, String color, String hText, String qText) {
//
//		OrganizeTemplateType template = null;
//		SealColor sColor = null;
//		for(OrganizeTemplateType organizeTemplateType : OrganizeTemplateType.values()){
//			if (templateType.equalsIgnoreCase(organizeTemplateType.template().disc())) {
//				template = organizeTemplateType;
//				break;
//			}
//		}
//		for(SealColor sealColor : SealColor.values()){
//			if (color.equalsIgnoreCase(sealColor.color().getColor())) {
//				sColor = sealColor;
//				break;
//			}
//		}
//		return sealService.addTemplateSeal(accountId, template, sColor, hText, qText);
//	}
	
//	@Override
//	public void createDocumentSummarySign(Long enterpriseId, String srcFile, String dstFile, String key) throws Exception {
//		SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterpriseId, SealTypeEnum.ENTERPRISE);  //查询企业信息
//		if(signatureEntity == null) {
//			throw new BusinessException(enterpriseId+"企业未注册e签宝");
//		}
//		LoginResult loginResult = esignsdkService.login();  //用户登录
//		SignPDFDocBean signPdf = new SignPDFDocBean(srcFile, dstFile, "", ConfigPropertites.getProperties("OWNERPASSWORD"));  //文档信息   可以选择文件流或 文件路径
//		SignSealBean seal = new SignSealBean(loginResult.getAccountId(),signatureEntity.getEaccount(), signatureEntity.getSealData(), false);   //签署所用的签章信息
//		PosBean signPos = new PosBean();//签章位置信息
//		//	    key="我们是社会主义国家";
//		signPos.setPosType(1).setKey(key);
//		Result rs = signService.localSignPDF(signPdf, seal, signPos, SignType.Key);  //用户摘要签署
//		LOG.info("用户签署结果" + rs.getErrCode() + ":" + rs.getMsg());
//	}

//	@Override
//	public FileDigestSignResult createDocumentSummarySignStream(Long enterpriseId,byte [] stream,String fileName,String key){
//		SignatureEntity signatureEntity=signatureService.inquireFinanceSignatureEntity(enterpriseId, SealTypeEnum.ENTERPRISE);  //查询企业信息
//		LoginResult loginResult = esignsdkService.login();  //用户登录
//		SignPDFDocBean signPdf=new SignPDFDocBean(stream, fileName,
//				ConfigPropertites.getProperties("OWNERPASSWORD"));  //文档信息   可以选择文件流或 文件路径
//		SignSealBean seal=new SignSealBean(loginResult.getAccountId(),signatureEntity.getEaccount(), 
//				signatureEntity.getSealData(), false);   //签署所用的签章信息
//		PosBean signPos = new PosBean();//签章位置信息
//		signPos.setPosType(1).setKey(key);
//		FileDigestSignResult rs=signService.localSignPDF(signPdf, seal, signPos, SignType.Key);  //用户摘要签署
//		LOG.info("用户签署结果"+rs.getErrCode()+":"+rs.getMsg());
//		return rs;
//	}
	
//	@Override
//	@Transactional
//	public void createEnterpriseDocumentSummarySign(Long enterpriseId, Long filesInfoId, String fileUuid, Integer sealType, String mobile, String code, String key) throws Exception {
//		if (enterpriseId == null) {
//			enterpriseId = FinanceSessionContext.getEnterpriseId();
//		}
//		SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterpriseId, SealTypeEnum.valueOf(sealType));  //查询企业信息
//		if(signatureEntity == null) {
//			throw new BusinessException(enterpriseId+"企业未注册e签宝");
//		}
//		LoginResult loginResult = esignsdkService.login();  //用户登录
//		
//		//签章位置
//		PosBean pos = new PosBean().setPosType(1).setKey(key);
//		//印章信息
//		SignSealBean seal=new SignSealBean(loginResult.getAccountId(),signatureEntity.getEaccount(), signatureEntity.getSealData(), false);
//		//文件信息
//		FileEntry fe = fileService.inquireFileEntry(fileUuid);
//		String filePath = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getUri();
//		File f = new File(filePath);
//		InputStream input = new FileInputStream(f);
//		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
//        byte[] buff = new byte[100];  
//        int rc = 0;  
//        while ((rc = input.read(buff, 0, 100)) > 0) {  
//            swapStream.write(buff, 0, rc);  
//        }  
//        byte[] stream = swapStream.toByteArray();  
////		SignPDFDocBean signPdf=new SignPDFDocBean(stream, fe.getFileName(), ConfigPropertites.getProperties("OWNERPASSWORD"));  //文档信息   可以选择文件流或 文件路径
////        SignPDFStreamBean signPdf = new SignPDFStreamBean();
////        signPdf.setStream(stream);
////        signPdf.setOwnerPassword(ConfigPropertites.getProperties("OWNERPASSWORD"));
////        signPdf.setFileName(fe.getFileName());
////		FileDigestSignResult rs=signService.localSignPDF(signPdf, seal, pos, SignType.Key);  //用户摘要签署
//        SignFileStreamResult rs = signService.localSafeSignPDF3rd(loginResult.getAccountId(), signatureEntity.getEaccount(), signatureEntity.getSealData(), stream, pos, SignType.Key, fe.getFileName(), mobile, code);
////		signService.localsafesignpdf3rd
////		SignFileStreamResult rs=signService.localSignPDF(loginResult.getAccountId(), signatureEntity.getEaccount(), signatureEntity.getSealData(), stream, pos, SignType.Key, fe.getFileName());  //用户摘要签署
//		LOG.info("用户签署结果"+rs.getErrCode()+":"+rs.getMsg());
//		if (rs.getErrCode() != 0) {
//			input.close();
//			throw new BusinessException(rs.getMsg());
//		}
//		FileEntry newFile = fileService.uploadFile(fe.getFileName(), new ByteArrayInputStream(rs.getStream()));
//		
//		SignFileInfoEntity sfie = new SignFileInfoEntity();
//		sfie.setFileUuid(newFile.getFileUuid());
//		sfie.setFileSignState(FileSignStateEnum.CLIENT_SIGN);
//		signFileInfoService.createSignFileInfo(sfie);
//		
//		FinanceFilesInfoEntity ffie = financeFilesInfoService.inquireFinanceFilesInfo(filesInfoId);
//		ffie.setFilesUuid(ffie.getFilesUuid().replace(fileUuid, newFile.getFileUuid()));
//		financeFilesInfoService.updateFinanceFilesInfo(ffie);
//		input.close();
//	}
	
	@Override
	@Transactional
	public void createEnterpriseDocumentSummarySignAll(Long enterpriseId, Long[] filesInfoId, String[] fileUuid, Integer sealType, String mobile, String code) throws Exception {
		if (enterpriseId == null) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		
		List<SignFileInfoEntity> sfies = new ArrayList<>();
		Boolean flag = Boolean.TRUE;
		for (int i = 0; i < filesInfoId.length; i++) {
//			FinanceFilesInfoEntity ffie = financeFilesInfoService.inquireFinanceFilesInfo(filesInfoId[i]);
			SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid[i]);
			if (StringUtils.isBlank(sfie.getFileUuid())) {
				sfie = new SignFileInfoEntity();
				sfie.setFileUuid(fileUuid[i]);
				sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
				signFileInfoService.createSignFileInfo(sfie);
			}
			sfies.add(sfie);
			Integer creatorType = null;
			if (FinanceSessionContext.isEnterprise()) {
				creatorType = 0;
			} else {
				creatorType = 1;
			}
			List<SignFileSealInfoEntity> sfsies = signFileSealInfoService.inquireSignFileSealInfoList(fileUuid[i], SignStateEnum.WAIT_SIGN, creatorType);
			if (sfsies == null || sfsies.size() == 0) {
				if (i == filesInfoId.length - 1) {
					throw new BusinessException("请先添加签署位置！");
				}
				continue;
			}
			for (int j = 0; j < sfsies.size(); j ++) {
				SignFileSealInfoEntity sfsie = sfsies.get(j);
				if (SignStateEnum.WAIT_SIGN != sfsie.getSignState()) {
					continue;
				}
				//文件信息
				FileEntry fe = fileService.inquireFileEntry(fileUuid[i]);
				String filePath = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getUri();
		        SignPDFFileBean signPdf = new SignPDFFileBean();
		        signPdf.setSrcPdfFile(filePath);//待签署PDF文档本地路径，含文档名
		        signPdf.setDstPdfFile(filePath);//签署后PDF文档本地路径，含文档名
//		        signPdf.setOwnerPassword(ConfigPropertites.getProperties("OWNERPASSWORD"));
				
				//签章位置
//				PosBean pos = new PosBean().setPosType(sfsie.getPosType()).setKey(sfsie.getKeyword()).setPosX(sfsie.getPosX()).setPosY(sfsie.getPosY());
//				pos.setWidth(sfsie.getObjectWidth());
		        PosBean pos = new PosBean().setPosType(sfsie.getPosType()).setPosX(sfsie.getPosX()).setPosY(sfsie.getPosY()).setPosPage(sfsie.getPage().toString());
				pos.setWidth(sfsie.getObjectWidth());
				if (sfsie.getSignType() == 2) {
					pos.setPosPage(sfsie.getPosPage());
				}
				
				//获取印章信息
				SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.valueOf(sealType));  //查询企业信息
				if(signatureEntity == null || StringUtil.isBlank(signatureEntity.getSealData())) {
					throw new BusinessException("您还未生成印章信息，请到我的签章处生成。");
				}
				
				SignatureDetail sealData = inquireSealDetail(enterpriseId, null, sfsie.getSealType().ordinal());
				FileDigestSignResult fdsr;
				if (flag) { //第一份文件需要提交验证码
					fdsr = userSignService.localSafeSignPDF3rd(signatureEntity.getEaccount(), sealData.getData(), signPdf, pos, SignType.from(sfsie.getSignType() + 1), mobile, code);
					if (fdsr.getErrCode() == 1 || fdsr.getErrCode() == 2) {
						throw new BusinessException(fdsr.getMsg());
					}
					flag = Boolean.FALSE;
				} else {
					fdsr = userSignService.localSignPDF(signatureEntity.getEaccount(), sealData.getData(), signPdf, pos, SignType.from(sfsie.getSignType() + 1));
				}
				LOG.info("PosBean:" + "posType:" + pos.getPosType() + "posX:" + pos.getPosX() + "posY:" + pos.getPosY() + "posPage:" + pos.getPosPage() + "width:" + pos.getWidth());
				LOG.info("Eaccount:" + (signatureEntity.getEaccount() + "sealData:" + sealData.getData() + "signType:" + SignType.from(sfsie.getSignType() + 1).name()));
				
				
//				CodeMultiSignResult cmsr = userSignService.localSafeMultiSignPDF3rd(signatureEntity.getEaccount(), signParams, sealData.getData(), mobile, code);
				
				LOG.info("用户签署结果" + fdsr.getErrCode() + ":" + fdsr.getMsg());
				
				if (fdsr.getErrCode() == 0) {
					sfsie.setSignState(SignStateEnum.SIGN_SUCCESS);
					sfsie.setSignResult(fdsr.getMsg());
					signFileSealInfoService.updateSignFileSealInfo(sfsie);
					
					sfie.setFileSignState(FileSignStateEnum.CLIENT_SIGN);
					sfie.setMsg("");
					signFileInfoService.updateSignFileInfo(sfie);
				} else {
					sfsie.setSignState(SignStateEnum.SIGN_FAILURE);
					sfsie.setSignResult(fdsr.getMsg());
					signFileSealInfoService.updateSignFileSealInfo(sfsie);
					
					sfie.setMsg(fdsr.getMsg());
					signFileInfoService.updateSignFileInfo(sfie);
				}
				
			}
		}
	}
	
	@Override
	@Transactional
	public void createPlatformDocumentSummarySignAll(Long financeId, Long[] filesInfoId, String[] fileUuid, Integer sealType) throws Exception {
		List<SignFileInfoEntity> sfies = new ArrayList<>();
		for (int i = 0; i < filesInfoId.length; i++) {
			SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid[i]);
			if (StringUtils.isBlank(sfie.getFileUuid())) {
				sfie = new SignFileInfoEntity();
				sfie.setFileUuid(fileUuid[i]);
				sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
				signFileInfoService.createSignFileInfo(sfie);
			}
			sfies.add(sfie);
			Integer creatorType = null;
			if (FinanceSessionContext.isEnterprise()) {
				creatorType = 0;
			} else {
				creatorType = 1;
			}
			List<SignFileSealInfoEntity> sfsies = signFileSealInfoService.inquireSignFileSealInfoList(fileUuid[i], SignStateEnum.WAIT_SIGN, creatorType);
			if (sfsies == null || sfsies.size() == 0) {
				if (i == filesInfoId.length - 1) {
					throw new BusinessException("请先添加签署位置！");
				}
				continue;
			}
			for (int j = 0; j < sfsies.size(); j ++) {
				SignFileSealInfoEntity sfsie = sfsies.get(j);
				if (SignStateEnum.WAIT_SIGN != sfsie.getSignState()) {
					continue;
				}
				//文件信息
				FileEntry fe = fileService.inquireFileEntry(fileUuid[i]);
				String filePath = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getUri();
		        SignPDFFileBean signPdf = new SignPDFFileBean();
		        signPdf.setSrcPdfFile(filePath);
		        signPdf.setDstPdfFile(filePath);
//		        signPdf.setOwnerPassword(ConfigPropertites.getProperties("OWNERPASSWORD"));
				
				//签章位置
				PosBean pos = new PosBean().setPosType(sfsie.getPosType()).setPosX(sfsie.getPosX()).setPosY(sfsie.getPosY()).setPosPage(sfsie.getPage().toString());
				pos.setWidth(sfsie.getObjectWidth());
				if (sfsie.getSignType() == 2) {
					pos.setPosPage(sfsie.getPosPage());
				}
				
				Integer s = 0;
				if (sfsie.getSealType() == SealTypeEnum.ENTERPRISE) {
					s = 29692;
				} else if (sfsie.getSealType() == SealTypeEnum.PERSONAL) {
					s = 29693;
				} else if (sfsie.getSealType() == SealTypeEnum.OTHERS) {
					s = 31140;
				}
				LOG.info("PosBean:" + "posType:" + pos.getPosType() + "posX:" + pos.getPosX() + "posY:" + pos.getPosY() + "posPage:" + pos.getPosPage());
				FileDigestSignResult fdsr = selfSignService.localSignPdf(signPdf, pos, s, SignType.from(sfsie.getSignType() + 1));
				
				LOG.info("平台签署结果" + fdsr.getErrCode() + ":" + fdsr.getMsg());
				
				if (fdsr.getErrCode() == 0) {
					sfsie.setSignState(SignStateEnum.SIGN_SUCCESS);
					sfsie.setSignResult(fdsr.getMsg());
					signFileSealInfoService.updateSignFileSealInfo(sfsie);
					
					sfie.setFileSignState(FileSignStateEnum.SIGNED);
					sfie.setMsg("");
					signFileInfoService.updateSignFileInfo(sfie);
					FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(financeId);
					finance.setFinanceConstractState(FinanceConstractStateEnum.PLATFORM_SIGNED);
					financeApplicationService.updateFinanceApplication(finance);
				} else {
					sfsie.setSignState(SignStateEnum.SIGN_FAILURE);
					sfsie.setSignResult(fdsr.getMsg());
					signFileSealInfoService.updateSignFileSealInfo(sfsie);
					
					sfie.setMsg(fdsr.getMsg());
					signFileInfoService.updateSignFileInfo(sfie);
				}
				
			}
		}
	}
	
	@Override
	@Transactional
	public void createWarehousePickupPlatformDocumentSummarySignAll(Long pickupId, Long[] filesInfoId,
			String[] fileUuid, Integer sealType) throws Exception {
		List<SignFileInfoEntity> sfies = new ArrayList<>();
		for (int i = 0; i < filesInfoId.length; i++) {
			SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid[i]);
			if (StringUtils.isBlank(sfie.getFileUuid())) {
				sfie = new SignFileInfoEntity();
				sfie.setFileUuid(fileUuid[i]);
				sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
				signFileInfoService.createSignFileInfo(sfie);
			}
			sfies.add(sfie);
			Integer creatorType = null;
			if (FinanceSessionContext.isEnterprise()) {
				creatorType = 0;
			} else {
				creatorType = 1;
			}
			List<SignFileSealInfoEntity> sfsies = signFileSealInfoService.inquireSignFileSealInfoList(fileUuid[i], SignStateEnum.WAIT_SIGN, creatorType);
			if (sfsies == null || sfsies.size() == 0) {
				if (i == filesInfoId.length - 1) {
					throw new BusinessException("请先添加签署位置！");
				}
				continue;
			}
			for (int j = 0; j < sfsies.size(); j ++) {
				SignFileSealInfoEntity sfsie = sfsies.get(j);
				if (SignStateEnum.WAIT_SIGN != sfsie.getSignState()) {
					continue;
				}
				//文件信息
				FileEntry fe = fileService.inquireFileEntry(fileUuid[i]);
				String filePath = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getUri();
		        SignPDFFileBean signPdf = new SignPDFFileBean();
		        signPdf.setSrcPdfFile(filePath);
		        signPdf.setDstPdfFile(filePath);
//		        signPdf.setOwnerPassword(ConfigPropertites.getProperties("OWNERPASSWORD"));
				
				//签章位置
				PosBean pos = new PosBean().setPosType(sfsie.getPosType()).setPosX(sfsie.getPosX()).setPosY(sfsie.getPosY()).setPosPage(sfsie.getPage().toString());
//				pos.setWidth(sfsie.getObjectWidth());
				if (sfsie.getSignType() == 2) {
					pos.setPosPage(sfsie.getPosPage());
				}
				
				Integer s = 0;
				if (sfsie.getSealType() == SealTypeEnum.ENTERPRISE) {
					s = 29692;
				} else if (sfsie.getSealType() == SealTypeEnum.PERSONAL) {
					s = 29693;
				} else if (sfsie.getSealType() == SealTypeEnum.OTHERS) {
					s = 31140;
				}
				FileDigestSignResult fdsr = selfSignService.localSignPdf(signPdf, pos, s, SignType.from(sfsie.getSignType() + 1));
				
				LOG.info("平台签署结果" + fdsr.getErrCode() + ":" + fdsr.getMsg());
				
				if (fdsr.getErrCode() == 0) {
					sfsie.setSignState(SignStateEnum.SIGN_SUCCESS);
					sfsie.setSignResult(fdsr.getMsg());
					signFileSealInfoService.updateSignFileSealInfo(sfsie);
					
					sfie.setFileSignState(FileSignStateEnum.SIGNED);
					sfie.setMsg("");
					signFileInfoService.updateSignFileInfo(sfie);
					PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
					pawe.setPickupState(WarePickupStateEnum.WAIT_RELEASE);
					pawe.setPickupState1(WarePickupStateEnum.PLATFORM_SIGNED);
					pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
				} else {
					sfsie.setSignState(SignStateEnum.SIGN_FAILURE);
					sfsie.setSignResult(fdsr.getMsg());
					signFileSealInfoService.updateSignFileSealInfo(sfsie);
					
					sfie.setMsg(fdsr.getMsg());
					signFileInfoService.updateSignFileInfo(sfie);
				}
				
			}
		}
	}

//	@Override
//	public void createSeflDocumentSummarySign(String srcFile, String dstFile, String key) throws Exception {
//		LoginResult loginResult = esignsdkService.login();  //用户登录
//		PosBean selfPos = new PosBean();//签章位置信息
//		selfPos.setPosType(1).setKey(key);
//		Result r = signService.localSignPDF(loginResult.getAccountId(), srcFile, dstFile, selfPos, 0, SignType.Key, "");  //0为默认为平台   fileName
//		LOG.info("用户签署结果" + r.getErrCode() + ":" + r.getMsg());
//	}

//	@Override
//	public FileDigestSignResult createSeflDocumentSummarySignStream(byte[] stream,
//			String fileName, String key){
//		LoginResult loginResult = esignsdkService.login();  //用户登录
//
//		SignPDFDocBean signPdf=new SignPDFDocBean(stream, fileName, ConfigPropertites.getProperties("OWNERPASSWORD"));  //文档信息   可以选择文件流或 文件路径
//		SignSealBean seal = new SignSealBean(loginResult.getAccountId(), 0);  //平台签
//		PosBean signPos = new PosBean();//签章位置信息 
//		signPos.setPosType(1).setKey(key);
//		FileDigestSignResult r = signService.localSignPDF(signPdf, seal, signPos, SignType.Key);
//		//    	Result r =signService.localSignPDF(loginResult.getAccountId(), stream, selfPos, 0, SignType.Key, ""); //0为默认为平台   fileName
//		LOG.info("平台签署结果" + r.getErrCode() + ":" + r.getMsg());
//		return r;
//	}
	
//	@Override
//	@Transactional
//	public void createPlatformDocumentSummarySign(Long filesInfoId, String fileUuid, String key)
//			throws Exception {
//		LoginResult loginResult = esignsdkService.login();  //用户登录
//		
//		//签章位置
//		PosBean pos = new PosBean().setPosType(1).setKey(key);
//		//印章信息
//		SignSealBean seal = new SignSealBean(loginResult.getAccountId(), 0);  //平台签
//		//文件信息
//		FileEntry fe = fileService.inquireFileEntry(fileUuid);
//		String filePath = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getUri();
//		File f = new File(filePath);
//		InputStream input = new FileInputStream(f);
//		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
//        byte[] buff = new byte[100];  
//        int rc = 0;  
//        while ((rc = input.read(buff, 0, 100)) > 0) {  
//            swapStream.write(buff, 0, rc);  
//        }  
//        byte[] stream = swapStream.toByteArray();  
//		SignPDFDocBean signPdf=new SignPDFDocBean(stream, fe.getFileName(), ConfigPropertites.getProperties("OWNERPASSWORD"));  //文档信息   可以选择文件流或 文件路径
//		FileDigestSignResult rs=signService.localSignPDF(signPdf, seal, pos, SignType.Key);  //用户摘要签署
//		LOG.info("用户签署结果"+rs.getErrCode()+":"+rs.getMsg());
//		if (rs.getErrCode() != 0) {
//			input.close();
//			throw new BusinessException(rs.getMsg());
//		}
//		FileEntry newFile = fileService.uploadFile(fe.getFileName(), new ByteArrayInputStream(rs.getStream()));
//		FinanceFilesInfoEntity ffie = financeFilesInfoService.inquireFinanceFilesInfo(filesInfoId);
//		ffie.setFilesUuid(ffie.getFilesUuid().replace(fileUuid, newFile.getFileUuid()));
//		ffie.setFileSignState(FileSignStateEnum.SIGNED);
//		financeFilesInfoService.updateFinanceFilesInfo(ffie);
//		input.close();
//		
//	}

	//	@Override
	//	public SignFileStreamResult platformSummarySignature(String devId, byte[] stream, PosBean signPos, int sealId,
	//			int signType, String fileName) {
	//		LoginResult loginResult = esignsdkService.login();  //用户登录

	//	    SignFileStreamResult s=signService.localSignPDF(devId,stream, signPos, sealId, signType, "fileName");

	//	    LOG.info("平台签署结果"+s.getErrCode()+":"+s.getMsg());
	//	    return s;
	//	}
//	@Override
//	public void saveSignedFile(Long enterpriseId, String docFilePath, String docName)
//			throws Exception {
//		SignatureEntity signatureEntity=signatureService.inquireFinanceSignatureEntity(enterpriseId, SealTypeEnum.ENTERPRISE);  //查询企业信息
//		if(signatureEntity==null)throw new Exception(enterpriseId+"企业未注册e签宝");
//		LoginResult loginResult = esignsdkService.login();  //用户登录
//		SignedFileResult saveFileResult = signService.saveSignedFile(loginResult.getAccountId(),
//				docFilePath, docName, new String[] { signatureEntity.getEaccount(),loginResult.getAccountId() });
//		LOG.info("用户文档保全结果"+saveFileResult.getErrCode()+":"+saveFileResult.getMsg());
//	}

	@Override
	public SignatureInfo inquireFinanceContractInfo(String fileUuid) throws IllegalAccessException, InvocationTargetException {
		FinanceSignatureInfoService financeSignatureInfoService=ComponentFactory.loadClass(FinanceSignatureInfoService.class);
		SignatureInfoEntity entity = financeSignatureInfoService.inquireFinanceSignatureInfoEntity(fileUuid);
		SignatureInfo info=new SignatureInfo();
		BeanUtils.copyProperties(entity, info);
		return info;
	}

//	@Override
//	public void saveSignedFile(Long enterpriseId, String docFilePath, String docName) throws Exception {
//		
//	}

	@Override
	public void sendSignCode3rd(String mobile){
		Long enterpriseId = FinanceSessionContext.getEnterpriseId();
		SignatureEntity signatureEntity = signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.ENTERPRISE);
		if(signatureEntity == null) {
			throw new BusinessException(enterpriseId+"企业未注册e签宝");
		}
		
		// 使用初始化设置的项目编号和项目验证码做项目账户登录
//		Result r = mobileService.sendSignCode3rd(loginResult.getAccountId(), signatureEntity.getEaccount(), mobile);//发送验证码
		Result r = mobileService.sendSignMobileCode3rd(signatureEntity.getEaccount(), mobile);
		LOG.info(r.getErrCode() + ":" + r.getMsg());
		if (r.getErrCode() != 0) {
			throw new BusinessException(r.getMsg());
		}
	}

	@Override
	@Transactional
	public void saveSealPos(Long[] signFileSealId, String[] fileUuid, String[] key, Integer[] sealType,
			Integer[] posType, String[] posPage, Integer[] page, Float[] posX, Float[] posY, Integer[] signType, Float[] flagX,
			Float[] flagY, Float[] width, Float[] height, Float[] marginLeft, Float[] marginTop) {
		
		for (int i = 0; i < signFileSealId.length; i++) {
			SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid[i]);
			if (sfie == null) {
				sfie = new SignFileInfoEntity();
				sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
				sfie.setFileUuid(fileUuid[i]);
				signFileInfoService.createSignFileInfo(sfie);
			}
			
			SignFileSealInfoEntity entity = signFileSealInfoService.inquireSignFileSealInfo(signFileSealId[i]);
			if (entity != null && entity.getSignState() != SignStateEnum.WAIT_SIGN) {
				continue;
			}
			if (entity == null) {
				entity = new SignFileSealInfoEntity();
			}
			if (1 == sealType[i]) {
				entity.setPosType(1);
				entity.setSignType(3);
				if (sealType[i] == 1) {
					entity.setObjectWidth(95f);
				}
				entity.setSealType(SealTypeEnum.valueOf(sealType[i]));
			}
			entity.setSealType(SealTypeEnum.valueOf(sealType[i]));
			entity.setSignType(signType[i]);
			entity.setFlagX(flagX[i]);
			entity.setFlagY(flagY[i]);
			entity.setPosX(posX[i]);
			entity.setPosY(posY[i]);
			entity.setPosPage(posPage[i]);
			entity.setWidth(width[i]);
			entity.setHeight(height[i]);
			entity.setMarginLeft(marginLeft[i]);
			entity.setMarginTop(marginTop[i]);
			entity.setPage(page[i]);
			if (FinanceSessionContext.isEnterprise()) {
				entity.setCreator(FinanceSessionContext.getEnterpriseName());
				entity.setCreatorType(0);
			} else {
				entity.setCreator(FinanceSessionContext.getAccountFullName());
				entity.setCreatorType(1);
			}
			entity.setKeyword(key[i]);
			entity.setFileUuid(fileUuid[i]);
			entity.setCreateDateTime(DateUtil.now());
			entity.setPosType(posType[i]);
			entity.setSignType(signType[i]);
			
			if (entity.getSignFileSealId() == null) {
				signFileSealInfoService.createSignFileSealInfo(entity);
			} else {
				signFileSealInfoService.updateSignFileSealInfo(entity);
			}
		}
	}
	
	@Override
	public SignFileSeals inquireWaitSignPos(String fileUuid, Long enterpriseId) throws Exception {
		SignFileSeals sfs = new SignFileSeals();
		Integer creatorType = null;
		if (enterpriseId != null || FinanceSessionContext.isEnterprise()) {
			creatorType = 0;
			if (enterpriseId == null) {
				enterpriseId = FinanceSessionContext.getEnterpriseId();
			}
		} else {
			creatorType = 1;
		}
		List<SignFileSealInfoEntity> sfsies = signFileSealInfoService.inquireSignFileSealInfoList(fileUuid, SignStateEnum.WAIT_SIGN, creatorType);
		for (SignFileSealInfoEntity sfsie : sfsies) {
			SignFileSealInfoDetail sfsid = new SignFileSealInfoDetail();
			BeanUtils.copyProperties(sfsie, sfsid);
			sfsid.setX(sfsie.getFlagX());
			sfsid.setY(sfsie.getFlagY());
//			sfsid.setFlagx(sfsie.getFlagX());
//			sfsid.setFlagy(sfsie.getFlagY());
			sfsid.setMargin_left(sfsie.getMarginLeft());
			sfsid.setMargin_top(sfsie.getMarginTop());
			sfsid.setSignState(sfsie.getSignState().ordinal());
			sfsid.setSeal(sfsie.getSealType().getValue());
			sfsid.setSealType(sfsie.getSealType().ordinal());
			if (sfsie.getSealType() == SealTypeEnum.PERSONAL) {
				sfsid.setObjheight(95f);
				sfsid.setObjwidth(95f);
			} else {
				sfsid.setObjheight(159f);
				sfsid.setObjwidth(159f);
			}
			if (0 == creatorType) {
				SignatureDetail sd = inquireSealDetail(enterpriseId, null, sfsie.getSealType().ordinal());
				sfsid.setFileUuid(sd.getSealSrc());
				sfsid.setImgSrc(sd.getSealSrc());
			} else {
				if (sfsie.getSealType() == SealTypeEnum.PERSONAL) {
					sfsid.setImgSrc("./fr.png");
				} else if (sfsie.getSealType() == SealTypeEnum.ENTERPRISE) {
					sfsid.setImgSrc("./gz.png");
				} else if (sfsie.getSealType() == SealTypeEnum.OTHERS) {
					sfsid.setImgSrc("./ht.png");
				}
			}
			sfsid.setSignType(sfsie.getSignType() + 1);
			sfs.getDatas().add(sfsid);
		}
		return sfs;
	}

	@Override
	@Transactional
	public void cancelSealPos(Long signFileSealId) {
		SignFileSealInfoEntity entity = signFileSealInfoService.inquireSignFileSealInfo(signFileSealId);
		entity.setSignState(SignStateEnum.CANCEL);
		signFileSealInfoService.updateSignFileSealInfo(entity);
	}

//	private BufferedImage resize(BufferedImage source, int targetW, int targetH) {
//		int type = source.getType();
//		BufferedImage target = null;
//		double sx = (double) targetW / source.getWidth();
//		double sy = (double) targetH / source.getHeight();
//		if (sx > sy) {
//			sx = sy;
//			targetW = (int) (sx * source.getWidth());
//		} else {
//			sy = sx;
//			targetH = (int) (sy * source.getHeight());
//		}
//		if (type == BufferedImage.TYPE_CUSTOM) {
//			ColorModel cm = source.getColorModel();
//			WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
//			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
//			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
//		} else {
//			target = new BufferedImage(targetW, targetH, type);
//		}
//		Graphics2D g = target.createGraphics();
//		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
//		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
//		g.dispose();
//		return target;
//	}
	
	@Override
	public SignPdfPicDetail getDocPic(String fileUuid) {
		SignPdfPicDetail sppd = new SignPdfPicDetail();
		
		//创建从中读取和向其中写入（可选）的随机访问文件流，R表示对其只是访问模式
		try {
			FileEntry fe = transferService.inquireFileEntry(fileUuid);
			File file = new File(ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getRelativePath());
			
			PDDocument doc = PDDocument.load(file);
			PDFRenderer renderer = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
//			String fileName = "";
			sppd.setDocName(fe.getFileName());
			sppd.setPageNum(pageCount);
			
			for (int i = 0; i < pageCount; i++) {
				SignPdfPagePicDetail spppd = new SignPdfPagePicDetail();
//				BufferedImage image = renderer.renderImageWithDPI(i, 300, ImageType.RGB); // Windows
																			// native
																			// DPI
				spppd.setPage(i+1);
				
				sppd.setPageWidth(new BigDecimal(renderer.renderImage(i).getWidth()));
				sppd.setPageHeight(new BigDecimal(renderer.renderImage(i).getHeight()));
//				BufferedImage srcImage = resize(image, 1240, 1750);// 产生缩略图
//				ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
//		        ImageIO.write(srcImage, "png", outputStream);  
//		        BASE64Encoder encoder = new BASE64Encoder();  
//		        String imageKey = "data:image/png;base64," + encoder.encode(outputStream.toByteArray());// 返回Base64编码过的字节数组字符串
		        String imageKey = "/finance/api/v1.0/getDocPicByPage.json?fileUuid=" + fileUuid + "&page=" + spppd.getPage();
		        
//		        if (imageKey!=null) {
//					Pattern p = Pattern.compile("\\s*|\t|\r|\n");
//					Matcher m = p.matcher(imageKey);
//					imageKey = m.replaceAll("");
//				}
				spppd.setImageKey(imageKey);
				sppd.getKeys().add(spppd);
			}
			doc.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sppd;
	}

	@Transactional
	@Override
	public void sealPictureSubmit(String fileUuid, Integer sealType) throws Exception {
		Long enterpriseId = FinanceSessionContext.getEnterpriseId();
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		if (AuthenticationEnum.ACSUCCESS != enterprise.getAuthentication()) {
			throw new BusinessException("未实名认证不可制章！");
		}
		
		// 使用初始化设置的项目编号和项目验证码做项目账户登录
		SignatureEntity signatureEntity=signatureService.inquireFinanceSignatureEntity(enterpriseId, null, SealTypeEnum.valueOf(sealType));
		
		if(signatureEntity != null) {
			if (AuditStateEnum.UNKNOWN != signatureEntity.getAuditState() && AuditStateEnum.REFUSE != signatureEntity.getAuditState() && AuditStateEnum.CALLBACK != signatureEntity.getAuditState()) {
				throw new BusinessException("已提交的签章不允许继续修改！");
			}
		}else {
			throw new BusinessException("印章信息获取失败！");
		}
		
		FileEntry fe = transferService.inquireFileEntry(fileUuid);
		File file = new File(ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getRelativePath());
		String imageKey = null;
		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int i = 0;
			while((i = fileInputStream.read(b)) != -1) {
				byteArrayOutputStream.write(b, 0, i);
			}
			byte[] byteArray = byteArrayOutputStream.toByteArray();
			BASE64Encoder encoder = new BASE64Encoder();
			imageKey = encoder.encode(byteArray);
			
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		signatureEntity.sethText(null);
		signatureEntity.setqText(null);
		signatureEntity.setSealData(imageKey);
		signatureEntity.setAuditState(AuditStateEnum.UNAUDIT);
		signatureEntity.setSubmitDateTime(DateUtil.now());
		signatureEntity.setModelType(2);
		signatureService.updateSignatureEntity(signatureEntity);
		
	}

	@Override
	public SignatureAuditRecordDetail inquirySignatureCallbackRecord(Long enterpriseId,
			Integer sealType, Integer recordType) {
		SignatureAuditRecordDetail signatureAuditRecordDetail = new SignatureAuditRecordDetail();
		if(enterpriseId == null) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		List<SignatureCallbackRecordEntity> signatureCallbackRecordList = signatureCallbackRecordService.inquirySignatureCallbackRecord(enterpriseId, sealType, recordType);
		if(signatureCallbackRecordList != null && signatureCallbackRecordList.size() > 0) {
			BeanUtils.copyProperties(signatureCallbackRecordList.get(signatureCallbackRecordList.size()-1), signatureAuditRecordDetail);
		}
		return signatureAuditRecordDetail;
	}
}
